package com.yx.gsyd.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yx.gsyd.comm.DictionaryEnum;
import com.yx.gsyd.comm.ResultEnum;
import com.yx.gsyd.config.WebResource;
import com.yx.gsyd.entity.SysManager;
import com.yx.gsyd.entity.SysRole;
import com.yx.gsyd.entity.req.SysManagerReq;
import com.yx.gsyd.entity.search.SysManagerSearch;
import com.yx.gsyd.entity.view.SysManagerView;
import com.yx.gsyd.exception.MyException;
import com.yx.gsyd.mapper.SysManagerMapper;
import com.yx.gsyd.qpage.QPage;
import com.yx.gsyd.redis.RedisService;
import com.yx.gsyd.satoken.StpUserUtil;
import com.yx.gsyd.service.*;
import com.yx.gsyd.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 后台账户表 服务实现类
 * </p>
 *
 * @author astupidcoder
 * @since 2021-06-16
 */
@Service
public class SysManagerServiceImpl extends ServiceImpl<SysManagerMapper, SysManager> implements ISysManagerService {

    @Autowired
    private ISysManagerRoleService iHjManagerRoleService;
    @Autowired
    private ISysRoleService iHjRoleService;
    @Autowired
    private RedisService redisService;

    @Autowired
    private WebResource webResource;


    /**
     * 获取管理用户列表
     * @param qPage
     * @param hjManagerSearch
     * @return
     */
    @Override
    public ResultView getListAll(QPage qPage, SysManagerSearch hjManagerSearch) {
        IPage iPage = new Page(qPage.getOffset(), qPage.getLimit());
        List<SysManagerView> mapList = this.baseMapper.getPageList(iPage,hjManagerSearch);
        return ResultView.ok(iPage.setRecords(mapList));
    }

    /**
     * 新增用户
     * @param hjManagerReq
     * @return
     */
    @Transactional
    @Override
    public ResultView addManager(SysManagerReq hjManagerReq) {
        String managerId= StpUtil.getLoginIdAsString();
        SysManager sysManager=this.getById(managerId);
        //检测当前账户是否存在
        SysManager exit=exitAccount(hjManagerReq.getMAccount());
        if(exit!=null){
            return ResultView.error("此账户已经存在");
        }
        SysManager hjManager=new SysManager();
        BeanUtils.copyProperties(hjManagerReq,hjManager);
        hjManager.setMPwd(RsaUtil.setRsaPwd(hjManagerReq.getMPwd()));
        hjManager.setManagerId(IdentityUtil.identityId("MA"));
        hjManager.setCtime(new Date());
        hjManager.setIsDel(DictionaryEnum.IS_DEL_N.getCode());
        hjManager.setAddManagerId(sysManager.getManagerId());
        String[] roleId=hjManagerReq.getRoleId();
        for (String s : roleId) {
            SysRole sysRole=this.iHjRoleService.getById(s);
            hjManager.setRoleName(sysRole.getRoleName());
            if(sysRole.getRoleName().equals("超级管理员")){
                hjManager.setMType(1);
            }else{
                if(sysRole.getRoleName().equals("服务中心主任")){
                    String date = DateUtils.getCurrentDateTime(DateUtils.DATE_FORMAT_UNSIGNED);
                    String imgName =hjManager.getManagerId() + ".png";
                    String context = webResource.getEquipmentPath() + hjManager.getManagerId();
                    String qrCodePath ="uploads/qrCode/" + date + "/" + imgName;
                    try {
                        QRCodeUtil.save(context, null, webResource.getStaticResourcePath() + qrCodePath);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    hjManager.setMQrcode(qrCodePath);
                    hjManager.setMType(2);
                }
                if(sysRole.getRoleName().equals("数据团队")){
                    hjManager.setMType(3);
                }
                if(sysRole.getRoleName().equals("交付团队")){
                    hjManager.setMType(4);
                }
                if(sysRole.getRoleName().equals("银行团队")){
                    hjManager.setMType(5);
                }
                if(sysRole.getRoleName().equals("员工")){
                    hjManager.setFjManagerId(hjManager.getParentManagerId());
                    if(sysManager.getMType()==1){
                        SysManager parent=this.getById(hjManager.getParentManagerId());
                        if(parent.getMType()==2){
                            String date = DateUtils.getCurrentDateTime(DateUtils.DATE_FORMAT_UNSIGNED);
                            String imgName =hjManager.getManagerId() + ".png";
                            String context = webResource.getEquipmentPath() + hjManager.getManagerId();
                            String qrCodePath ="uploads/qrCode/" + date + "/" + imgName;
                            try {
                                QRCodeUtil.save(context, null, webResource.getStaticResourcePath() + qrCodePath);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            hjManager.setMQrcode(qrCodePath);
                        }else if(parent.getMType()==5){
                            if(StringUtils.isNotBlank(hjManagerReq.getParentsManagerId())){//证明是所属支行
                                hjManager.setParentManagerId(hjManagerReq.getParentsManagerId());
                            }
                        }
                    }else if(sysManager.getMType()==2){//服务中心众人
                        String date = DateUtils.getCurrentDateTime(DateUtils.DATE_FORMAT_UNSIGNED);
                        String imgName =hjManager.getManagerId() + ".png";
                        String context = webResource.getEquipmentPath() + hjManager.getManagerId();
                        String qrCodePath ="uploads/qrCode/" + date + "/" + imgName;
                        try {
                            QRCodeUtil.save(context, null, webResource.getStaticResourcePath() + qrCodePath);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        hjManager.setMQrcode(qrCodePath);
                        hjManager.setParentManagerId(managerId);
                    }else if(sysManager.getMType()==5){//银行团队
                        if(StringUtils.isNotBlank(hjManagerReq.getParentsManagerId())){//证明是所属支行
                            hjManager.setParentManagerId(hjManagerReq.getParentsManagerId());
                        }
                    }else if(sysManager.getMType()==6){//支行员工的情况下
                        SysManager pManagerId=this.getById(sysManager.getParentManagerId());
                        if(pManagerId.getMType()==5){//如果他的上级是银行
                            hjManager.setFjManagerId(pManagerId.getParentManagerId());
                            hjManager.setParentManagerId(sysManager.getManagerId());
                        }
                    }
                    hjManager.setMType(6);
                }
            }
        }
        boolean count=this.save(hjManager);
        if(!count){
            throw new MyException(ResultEnum.CODE_2,"添加用户出现异常");
        }
        //新增用户角色关联表
        boolean isOk=this.iHjManagerRoleService.saveRoleUser(hjManagerReq.getRoleId(),hjManager.getManagerId());
        if(!isOk){
            throw new MyException(ResultEnum.CODE_2,"添加用户角色关联出现异常");
        }
        return ResultView.ok();
    }

    /**
     * 检测当前账户是否存在
     * @param account
     * @return
     */
    @Override
    public SysManager exitAccount(String account) {
        QueryWrapper<SysManager> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("m_account",account);
        queryWrapper.eq("is_del",DictionaryEnum.IS_DEL_N.getCode());
        SysManager hjManager=this.getOne(queryWrapper);
        return hjManager;
    }

    /**
     * 启用或停用账户
     * @param managerId
     * @return
     */
    @Override
    public ResultView applyStatus(String managerId) {
        SysManager hjManager=this.getById(managerId);
        if(hjManager==null){
            return ResultView.error("账户不存在");
        }
        if(hjManager.getMStatus()==DictionaryEnum.IS_ENABLE_N.getCode()){
            hjManager.setMStatus(DictionaryEnum.IS_ENABLE_Y.getCode());
        }else{
            hjManager.setMStatus(DictionaryEnum.IS_ENABLE_N.getCode());
        }
        boolean isOk=this.updateById(hjManager);
        if(!isOk){
            throw new MyException(ResultEnum.CODE_2,"状态更新异常");
        }
        return ResultView.ok();
    }

    /**
     * 重置密码
     * @param mPwd 账户ID
     * @param mPwd 密码
     * @return
     */
    @Override
    public ResultView restPwd(String mPwd, String newPwd) {
        SysManager hjManager=this.getById(StpUtil.getLoginIdAsString());
        if(hjManager==null){
            return ResultView.error("账户不存在");
        }
        if(!RsaUtil.getRsaPwd(hjManager.getMPwd()).equals(mPwd)){
            return ResultView.error("旧密码验证不匹配");
        }
        hjManager.setMPwd(RsaUtil.setRsaPwd(newPwd));
        boolean isOk=this.updateById(hjManager);
        if(!isOk){
            throw new MyException(ResultEnum.CODE_2,"重置密码更新异常");
        }
        return ResultView.ok();
    }

    /**
     * 重置密码
     * @param mPwd 账户ID
     * @param mPwd 密码
     * @return
     */
    @Override
    public ResultView restAppPwd(String mPwd, String newPwd) {
        SysManager hjManager=this.getById(StpUserUtil.getLoginIdAsString());
        if(hjManager==null){
            return ResultView.error("账户不存在");
        }
        if(!RsaUtil.getRsaPwd(hjManager.getMPwd()).equals(mPwd)){
            return ResultView.error("旧密码验证不匹配");
        }
        hjManager.setMPwd(RsaUtil.setRsaPwd(newPwd));
        boolean isOk=this.updateById(hjManager);
        if(!isOk){
            throw new MyException(ResultEnum.CODE_2,"重置密码更新异常");
        }
        return ResultView.ok();
    }

    /**
     * 删除用户
     * @param managerId
     * @return
     */
    @Override
    public ResultView deleteManager(String managerId) {
        SysManager hjManager=this.getById(managerId);
        if(hjManager==null){
            return ResultView.error("账户不存在");
        }
        hjManager.setIsDel(DictionaryEnum.IS_DEL_Y.getCode());
        boolean isOk=this.updateById(hjManager);
        if(!isOk){
            throw new MyException(ResultEnum.CODE_2,"删除用户异常");
        }
        return ResultView.ok();
    }

    /**
     * 根据账户ID获取当前账户信息
     * @return
     */
    @Override
    public ResultView getManagerId(String managerId) {
        Map<String,Object> map=new HashMap<>();
        //获取当前用户信息
        SysManager hjManager=this.getById(managerId);
        SysManagerView sysManagerView=new SysManagerView();
        BeanUtils.copyProperties(hjManager,sysManagerView);
        if(sysManagerView.getParentManagerId()!=null&&!sysManagerView.getParentManagerId().equals("")){
            SysManager parentMan=this.getById(sysManagerView.getParentManagerId());//获取当前账号上级银行的名称
            if(StringUtils.isNotBlank(parentMan.getParentManagerId())){//网点
                SysManager parentsMan=this.getById(parentMan.getParentManagerId());

                sysManagerView.setParentsManagerName(parentMan.getMName());
                sysManagerView.setParentsType(parentMan.getMType());
                sysManagerView.setParentsManagerId(parentMan.getManagerId());

                sysManagerView.setParentManagerId(parentsMan.getManagerId());
                sysManagerView.setParentManagerName(parentsMan.getMName());
                sysManagerView.setParentType(parentsMan.getMType());
            }else{
                sysManagerView.setParentManagerName(parentMan.getMName());
                sysManagerView.setParentType(parentMan.getMType());
            }
        }
        map.put("hjManager",sysManagerView);
        //获取系统中所有的角色
        List<SysRole> roles=this.iHjRoleService.getListAll();
        map.put("roles",roles);
        //获取当前用户已经绑定的角色
        List<Object> roleManager=iHjManagerRoleService.getByRoleId(managerId);
        map.put("roleManager",roleManager);
        return ResultView.ok(map);
    }

    /**
     * 修改账户
     * @param hjManagerReq
     * @return
     */
    @Transactional
    @Override
    public ResultView updateManager(SysManagerReq hjManagerReq) {
        String managerId= StpUtil.getLoginIdAsString();
        SysManager dto=this.getById(managerId);
        SysManager hjManager=new SysManager();
        BeanUtils.copyProperties(hjManagerReq,hjManager);
        hjManager.setUtime(new Date());
        if(hjManagerReq.getMPwd()!=null&&!hjManagerReq.getMPwd().equals("")){
            hjManager.setMPwd(RsaUtil.setRsaPwd(hjManagerReq.getMPwd()));
        }
        hjManager.setUpdateManagerId(dto.getUpdateManagerId());
        String[] roleId=hjManagerReq.getRoleId();
        for (String s : roleId) {
            SysRole sysRole=this.iHjRoleService.getById(s);
            hjManager.setRoleName(sysRole.getRoleName());
            if(sysRole.getRoleName().equals("超级管理员")){
                hjManager.setMType(1);
            }else{
                if(sysRole.getRoleName().equals("服务中心主任")){
                    String date = DateUtils.getCurrentDateTime(DateUtils.DATE_FORMAT_UNSIGNED);
                    String imgName =hjManager.getManagerId() + ".png";
                    String context = webResource.getEquipmentPath() + hjManager.getManagerId();
                    String qrCodePath ="uploads/qrCode/" + date + "/" + imgName;
                    try {
                        QRCodeUtil.save(context, null, webResource.getStaticResourcePath() + qrCodePath);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    hjManager.setMQrcode(qrCodePath);
                    hjManager.setMType(2);
                }
                if(sysRole.getRoleName().equals("数据团队")){
                    hjManager.setMType(3);
                }
                if(sysRole.getRoleName().equals("交付团队")){
                    hjManager.setMType(4);
                }
                if(sysRole.getRoleName().equals("银行团队")){
                    hjManager.setMType(5);
                }
                if(sysRole.getRoleName().equals("员工")){
                    hjManager.setFjManagerId(hjManager.getParentManagerId());
                    if(dto.getMType()==1){
                        SysManager parent=this.getById(hjManager.getParentManagerId());
                        if(parent.getMType()==2){
                            String date = DateUtils.getCurrentDateTime(DateUtils.DATE_FORMAT_UNSIGNED);
                            String imgName =hjManager.getManagerId() + ".png";
                            String context = webResource.getEquipmentPath() + hjManager.getManagerId();
                            String qrCodePath ="uploads/qrCode/" + date + "/" + imgName;
                            try {
                                QRCodeUtil.save(context, null, webResource.getStaticResourcePath() + qrCodePath);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            hjManager.setMQrcode(qrCodePath);
                        }else if(parent.getMType()==5){
                            if(StringUtils.isNotBlank(hjManagerReq.getParentsManagerId())){//证明是所属支行
                                hjManager.setParentManagerId(hjManagerReq.getParentsManagerId());
                            }
                        }
                    }else if(dto.getMType()==2){
                        String date = DateUtils.getCurrentDateTime(DateUtils.DATE_FORMAT_UNSIGNED);
                        String imgName =hjManager.getManagerId() + ".png";
                        String context = webResource.getEquipmentPath() + hjManager.getManagerId();
                        String qrCodePath ="uploads/qrCode/" + date + "/" + imgName;
                        try {
                            QRCodeUtil.save(context, null, webResource.getStaticResourcePath() + qrCodePath);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        hjManager.setMQrcode(qrCodePath);
                        hjManager.setParentManagerId(managerId);
                    }else if(dto.getMType()==5){//银行团队
                        if(StringUtils.isNotBlank(hjManagerReq.getParentsManagerId())){//证明是所属支行
                            hjManager.setParentManagerId(hjManagerReq.getParentsManagerId());
                        }
                    }else if(dto.getMType()==6){//支行员工的情况下
                        SysManager pManagerId=this.getById(dto.getParentManagerId());
                        if(pManagerId.getMType()==5){//如果他的上级是银行
                            hjManager.setFjManagerId(pManagerId.getParentManagerId());
                            hjManager.setParentManagerId(dto.getManagerId());
                        }
                    }
                    hjManager.setMType(6);
                }

            }
        }
        boolean count=this.updateById(hjManager);
        if(!count){
            throw new MyException(ResultEnum.CODE_2,"修改账户出现异常");
        }
        //删除之前关联这个账户关联的角色数据
        this.iHjManagerRoleService.removeManagerRoleId(hjManagerReq.getManagerId());
        //新增用户角色关联表
        boolean isOk=this.iHjManagerRoleService.saveRoleUser(hjManagerReq.getRoleId(),hjManagerReq.getManagerId());
        if(!isOk){
            throw new MyException(ResultEnum.CODE_2,"添加用户角色关联出现异常");
        }
        return ResultView.ok();
    }

    /**
     * 批量删除用户
     * @param managerId
     * @return
     */
    @Override
    public ResultView batchDeleteManager(String[] managerId) {
        List<SysManager> hjManagerList=new ArrayList<>();
        for (String mId : managerId) {
            SysManager hjManager=new SysManager();
            hjManager.setManagerId(mId);
            hjManager.setIsDel(DictionaryEnum.IS_DEL_Y.getCode());
            hjManagerList.add(hjManager);
        }
        boolean isOk=this.updateBatchById(hjManagerList);
        if(!isOk){
            throw new MyException(ResultEnum.CODE_2,"批量删除用户出现异常");
        }
        return ResultView.ok();
    }

    /**
     * 导出账户
     * @param search
     * @return
     */
    @Override
    public List<SysManagerView> downLoadList(SysManagerSearch search) {
        return this.baseMapper.downLoadList(search);
    }


}
